//@Time:2022/4/2 14:02
//@Author:aFun

package indi.csms_springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import indi.csms_springboot.domain.User;
import indi.csms_springboot.mapper.UserMapper;
import indi.csms_springboot.service.loginMethod.*;
import indi.csms_springboot.service.LoginService;
import indi.csms_springboot.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Override
    public R login(User user) {
        String account=user.getAccount();
        String password=user.getPassword();
        try {
            // 使用MD5进行解密
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String finalPassword = base64Encoder.encode(md5.digest(password.getBytes("utf-8")));

            Map<String,Object> params=new HashMap<>();
            params.put("account",account);
            params.put("password",finalPassword);
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.allEq((k,v)->(k.equals("account")||k.equals("password")),params);
            User userRet = this.userMapper.selectOne(wrapper);
            if(userRet!=null){
                return new R(true,userRet);
            }else{
                return new R(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public R findPasswordByAccount(User user) {
        Map<String,Object> params=new HashMap<>();
        params.put("account",user.getAccount());
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.allEq((k,v)->(k.equals("account")),params);
        User user1 = userMapper.selectOne(wrapper);
        if(user1!=null){
            return new R(true,user1.getPassword());
        }else{
            return new R(false);
        }

    }

    @Override
    public R alterPassword(User user,String oldPwd){
        // 使用MD5进行加密
        MessageDigest md5 = null;

        // 先验证旧密码是否正确
        // 通过账号找到旧密码
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        String databaseOldPwd = userMapper.selectOne(queryWrapper).getPassword();

        try {
            md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64Encoder = new BASE64Encoder();

            // 将传进来的旧密码与数据库密码对比
            String finalOldPwd = base64Encoder.encode(md5.digest(oldPwd.getBytes(StandardCharsets.UTF_8)));
            if(finalOldPwd.equals(databaseOldPwd)){
                // 旧密码正确
                // 密码可以为空，默认为123456
                String psd = user.getPassword().equals("") ? "123456" : user.getPassword();
                String finalPsd = base64Encoder.encode(md5.digest(psd.getBytes("utf-8")));
                user.setPassword(finalPsd);
                Map<String,Object> params=new HashMap<>();
                params.put("account",user.getAccount());
                QueryWrapper<User> wrapper=new QueryWrapper<>();
                wrapper.eq("account",user.getAccount());
                int update = userMapper.update(user, wrapper);
                return update>0?new R(true):new R(false,"数据库异常！");
            }else{
                // 旧密码错误
                return new R(false,"旧密码错误！");
            }


        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new R(false);
    }

    @Override
    public R stragyMethodForRole(User user) {
        MethodForLogin mfl = null;
        switch (user.getRoleId()) {
            case 1:
                mfl = new ManagerLogin();
                break;
            case 2:
                mfl = new OfficerLogin();
                break;
            case 3:
                mfl = new TeacherLogin();
                break;
            case 4:
                mfl = new StudentLogin();
                break;
            default:
                break;
        }
        if (mfl == null) {
            return new R(false);
        } else {
            R r = new R();
            r.setData(mfl.roleLogin(user));
            r.setFlag(true);
            return r;
        }
    }

}
